package com.xunji.standard.controller;

import com.xunji.standard.common.Constant;
import com.xunji.standard.common.R;
import com.xunji.standard.entity.CaseUploadInfo;
import com.xunji.standard.entity.NdAnalysisData;
import com.xunji.standard.service.CaseService;
import com.xunji.standard.service.CaseUploadInfoService;
import com.xunji.standard.service.NdAnalysisDataService;
import com.xunji.standard.vo.rep.NdAnalysisDataResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: xuqiang_imyours
 * @Date: 2025/7/7 15:54
 * @Description:
 **/
@Slf4j
@Api(tags = "文件解析")
@RestController
@RequestMapping("/nad")
public class NdAnalysisDataController {
    @Resource
    private NdAnalysisDataService ndAnalysisDataService;
    @Resource
    private CaseService caseService;
    @Resource
    private CaseUploadInfoService caseUploadInfoService;

    @GetMapping("/log/{caseId}")
    @ApiOperation(value = "解析日志查询", notes = "解析日志查询")
    public R dataLog(@PathVariable String caseId) {

        // 取出所有上传号
        List<CaseUploadInfo> infos = caseUploadInfoService.getListByCaseId(caseId);
        if (infos == null || infos.isEmpty()) return R.failure("案件不存在!");
        // 取出倒排第一个,判断状态
        CaseUploadInfo info = infos.get(0);
        Long infoId = info.getId();
        Integer status = info.getStatus();
        if (status == 1) return R.failure("文件解密中,尚未开始解析!");

        NdAnalysisDataResponse ndr = new NdAnalysisDataResponse();
        ndr.setCaseId(caseId);
        if (status == Constant.I_TWO) {
            // 文件解析中
            List<NdAnalysisData> list = ndAnalysisDataService.getListByInfoIdAndCaseId(caseId, infoId);
            ndr.setJxzt(Constant.I_ZERO); // 解析中
            if (list != null && !list.isEmpty()) {
                NdAnalysisData ndAnalysisData = list.get(0); // 取出最新的一条记录,根据状态记录上传号状态
                Integer jxzt = ndAnalysisData.getJxzt();
                if (jxzt == 1) {  // 解析已完成,记录状态
                    caseUploadInfoService.updateStatusById(infoId, Constant.I_ZERO); // 解析完成
                }

                for (NdAnalysisData item : list) {
                    String jxrz = item.getJxrz();
                    String ywj = item.getYwj();
                    // 取出源文件的名称
                    String fileName = "";
                    if (!StringUtils.isEmpty(ywj)) {
                        fileName = ywj.substring(ywj.lastIndexOf(File.separator) + 1);
                    }
                    item.setJxrz(jxrz + "：" + fileName);
                    item.setYwj(fileName);
                }
                ndr.setLogs(list);
                // 计算百分比
                ArrayList<String> data = new ArrayList<>();
                for (NdAnalysisData item : list) {
                    data.add(item.getJxrz());
                }
                ndr.setPercentage(getMaxPercentage(data));
            } else {
                ndr.setLogs(null);
                ndr.setPercentage(0);
            }
        } else if (status == Constant.I_ZERO) { // 解密完成
            ndr.setJxzt(Constant.I_ONE); // 解析完成
            ndr.setLogs(null);
            ndr.setPercentage(100);
        }

        return R.success(ndr);
    }


    /**
     * 正则匹配计算最大百分比
     *
     * @param data
     * @return
     */
    public double getMaxPercentage(List<String> data) {
        double maxPercentage = 0.0;
        Pattern pattern = Pattern.compile("(\\d+)/(\\d+)");

        for (String item : data) {
            if (item == null) continue;

            Matcher matcher = pattern.matcher(item);
            if (matcher.find()) {
                double numerator = Double.parseDouble(matcher.group(1));
                double denominator = Double.parseDouble(matcher.group(2));

                if (denominator != 0) {
                    double percentage = (numerator / denominator) * 100;
                    maxPercentage = Math.max(maxPercentage, percentage);
                }
            }
        }
        return Double.parseDouble(String.format("%.2f", maxPercentage));
    }
}
